# 引入依赖
from concurrent.futures import ProcessPoolExecutor
import time, os
import requests
import random


def task(name):
    print("%s %s is running" % (name, os.getpid()))
    time.sleep(random.randint(1, 3))


if __name__ == '__main__':
    p = ProcessPoolExecutor(4)  # 设置进程池内进程
    for i in range(10):
        # 异步调用方式，只调用，不等返回值
        p.submit(task, '进程pid：')  # 传参方式(任务名,参数),参数使用位置参数或者关键字参数
    p.shutdown(wait=True)  # 关闭进程池的入口，等待池内任务运行结束
    print('主')


##################
##################
# 另一个异步调用的demo
def get(url):
    print('%s GET %s' % (os.getpid(), url))
    time.sleep(3)
    reponse = requests.get(url)
    if reponse.status_code == 200:
        res = reponse.text
    else:
        res = "下载失败"
    parse(res)  # 没有返回值


def parse(res):
    time.sleep(1)
    print('%s 解析结果为%s' % (os.getpid(), len(res)))


if __name__ == '__main__':
    urls = [
        'https://www.baidu.com',
        'https://www.sina.com.cn',
        'https://www.tmall.com',
        'https://www.jd.com',
        'https://www.python.org',
        'https://www.openstack.org',
        'https://www.baidu.com',
        'https://www.baidu.com',
        'https://www.baidu.com',

    ]
    p = ProcessPoolExecutor(9)
    start = time.time()
    for url in urls:
        future = p.submit(get, url)
    p.shutdown(wait=True)
    print("完成时间", time.time() - start)  # 完成时间 6.293345212936401